#coding:utf-8
from __future__ import division
import math
import datetime
from django.db.models import Q
from haystack.query import SearchQuerySet
import operator
from lovewith.share.models import *
from lovewith.settings import PAGE_SIZE
from lovewith.utils.image import MtImage
from lovewith.utils.mtcache import MtCache
from lovewith.utils.tools import my_iterator
from lovewith.share.views.modules.attach_tag import AttachTagApi
from lovewith.share.views.modules.attach_flag import AttachFlagApi
from lovewith.share.views.modules.attach_like import AttachLikeApi
from lovewith.share.views.modules.attach_color import AttachColorApi
from lovewith.share.views.modules.attach import AttachApi
from lovewith.website.views.modules.color import ColorApi


#分享
class ShareApi:
    def __init__(self):
        self.page_size = PAGE_SIZE

    #校验share数据
    @staticmethod
    def check_data(share_id):
        share_id = int(share_id)
        share_data = Post.objects.filter(id=int(share_id))
        if share_data.exists():
            return share_data[0]

        return None

    #分享总数
    @staticmethod
    def get_total():
        post_total = MtCache('site_post_total').get()
        if not post_total:
            post_total = Post.objects.all().count()
            MtCache('site_post_total').set(post_total)

        return post_total

    #根据每张图片的颜色、标签数据
    @staticmethod
    def get_ext_data(image_id):
        image_data = AttachApi.check_data(image_id)
        if image_data:
            cate_data = MtCache('image_ext_data').get(image_id=image_id)
            if not cate_data:
                ext_data = AttachApi().get_ext_data(image_data.id)
                #分享数据
                cate_data = {
                    'image': {
                        'id': image_data.id,
                        'path': image_data.path,
                        #'base_like_num': AttachLikeApi.get_total_by_image(image_id),
                        'post_id': image_data.share_post.id,
                        'is_cover': image_data.is_cover,
                    },
                    'colors': ext_data.get('colors'),  # 颜色
                    'tags': ext_data.get('tags'),  # tag
                    'taoke_data': ext_data.get('tks'),  # 淘客
                    'sc_data': ext_data.get('origins')  # 商品
                }

                MtCache('image_ext_data').set(cate_data, image_id=image_id)

            return cate_data

        return None

    #获取分类的灵感数据(有分页)
    @staticmethod
    def get_by_cate(cate_id, page_no, content_type='new'):
        cate_data = MtCache('cate_share').get(cate_id=cate_id, page=page_no, type=content_type)

        if not cate_data:
            new_page_no = page_no
            #记录总数
            total = Post.objects.filter(is_delete=False, cate_id=int(cate_id)).count()
            if content_type == 'selected':
                total = Post.objects.filter(is_delete=False, cate_id=int(cate_id), is_recommend=1).count()

            #总页数
            total_page = int(math.ceil(total / PAGE_SIZE))
            total_page = 1 and total_page or 1

            start = (new_page_no - 1) * PAGE_SIZE
            last = new_page_no * PAGE_SIZE

            if last > total:
                last = total

            all_cate_data = []

            share_filter_data = Post.objects.filter(is_delete=False, cate_id=int(cate_id))
            if content_type == 'selected':
                share_filter_data = Post.objects.filter(is_delete=False, cate_id=int(cate_id), is_recommend=1)

            share_filter_data = share_filter_data.order_by('-post_date')[start: last]

            for share in my_iterator(share_filter_data):
                cover_data = AttachApi().get_cover_by_share(share.id)
                if cover_data:
                    all_cate_data.append(cover_data)

            cate_data = {'share': all_cate_data, 'total': total, 'data_page': new_page_no, 'total_page': total_page}

            MtCache('cate_share').set(cate_data, cate_id=cate_id, page=page_no, type=content_type)
        return cate_data

    #获取用户分享的帖子总数
    @staticmethod
    def get_total_post_by_user(uid):
        return Post.objects.filter(is_delete=False, user_id=int(uid)).count()

    #获取用户分享的帖子
    def get_post_by_user(self, user_id, page_no):
        post_data = MtCache('user_post').get(user_id=user_id, page=page_no)

        if not post_data:
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE
            total = self.get_total_post_by_user(user_id)
            if last > total:
                last = total

            all_post_data = []
            share_data = Post.objects.filter(is_delete=False, user_id=int(user_id)).order_by('-id')[start: last]
            for share in my_iterator(share_data):
                user_cover_data = AttachApi().get_cover_by_share(share.id)
                if user_cover_data:
                    user_cover_data.update({
                        'title': share.title,
                        'uid': share.user.id,
                        'name': share.user.username,
                        'avatar': share.user.avatar,
                        'is_video': share.is_video,
                        'video': share.video
                    })
                all_post_data.append(user_cover_data)

            post_data = {'share': all_post_data, 'total': total}

            MtCache('user_post').set(post_data, user_id=user_id, page=page_no)
        return post_data

    #获取用户like的帖子数据
    @staticmethod
    def get_like_by_user(user_id, page_no):
        like_data = MtCache('user_like').get(user_id=user_id, page=page_no)
        if not like_data:
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE
            total = AttachLikeApi.get_total_by_user(user_id)
            if last > total:
                last = total

            all_like_data = AttachLikeApi.get_by_user(user_id, start, last)

            like_data = {'share': all_like_data, 'total': total}
            MtCache('user_like').set(like_data, user_id=user_id, page=page_no)
        return like_data

    #获取昨天的分享
    @staticmethod
    def get_yesterday():
        yesterday = datetime.date.today() - datetime.timedelta(days=1)
        return Post.objects.filter(post_date__startswith=str(yesterday)).order_by('-id')

    #删除分享
    @staticmethod
    def delete(share_data):
        share_data.is_delete = 1
        share_data.save()
        #删除图片
        #image_data = AttachApi.get_by_share(share_data.id)
        #for img in image_data:
        #    AttachApi().delete(img.id)

        #分享数据
        #share_data.delete()

    #合并图片
    def get_combo_image(self, share_id):
        share_data = self.check_data(share_id)
        if not share_data:
            return None
        else:
            #已经存在合并的图片
            if share_data.combo_path:
                return share_data.combo_path
            else:
                return MtImage().combo_images_by_share(share_id)

    #根据tag搜索
    @staticmethod
    def get_by_tag(search_tag, page_no=1):
        #未指定用户名时按tag搜索
        tag_share_data = MtCache('search_tag').get(tag=search_tag, page=page_no)

        if not tag_share_data:
            post_data = []
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE
            total = AttachTagApi.get_search_count(search_tag)
            if last > total:
                last = total

            tag_data = AttachTagApi.search(search_tag, start, last)
            for tag in my_iterator(tag_data):
                cover_data = AttachApi().get_cover_by_share(tag.post_image.share_post.id)

                #tk数据
                img_sale_data = AttachFlagApi.get_goods_by_image(tag.post_image.id)
                if img_sale_data:
                    img_sale_data = img_sale_data[0]
                else:
                    img_sale_data = None

                cover_data.update({
                    'cover': tag.post_image.path,
                    'cover_id': tag.post_image.id,
                    'sale_data': img_sale_data
                })
                post_data.append(cover_data)

            tag_share_data = {'share': post_data, 'total': total}

            MtCache('search_tag').set(tag_share_data, tag=search_tag, page=page_no)

        return tag_share_data

    #根据keyword搜索
    @staticmethod
    def get_by_title(keyword, page_no):
        key_share_data = MtCache('search_keyword').get(keyword=keyword, page=page_no)
        if not key_share_data:
            all_post_data = []
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE

            if keyword.find(' ') > -1:
                #简单拆词
                keyword_list = keyword.split(' ')
                q_list = []
                for k in keyword_list:
                    q_list.append(Q(title__icontains=k.strip()))

                post_filter_data = Post.objects.filter(reduce(operator.and_, q_list)).filter(is_delete=False)
            else:
                #替换为Haystack搜索
                post_filter_data = Post.objects.filter(Q(title__icontains=keyword) | Q(content__icontains=keyword)).filter(is_delete=False)
                #post_filter_data = SearchQuerySet().filter(content=keyword).order_by('-id')

            total = post_filter_data.count()

            if last > total:
                last = total

            post_data = post_filter_data.order_by('-post_date')[start: last]

            for post in post_data:
                cover_data = AttachApi().get_cover_by_share(post.pk)
                all_post_data.append(cover_data)

            key_share_data = {'share': all_post_data, 'total': total}
            MtCache('search_keyword').set(key_share_data, keyword=keyword, page=page_no)

        return key_share_data

    #根据color搜索
    @staticmethod
    def get_by_color(color, page_no):
        color_share_data = MtCache('search_color').get(color=color, page=page_no)
        if not color_share_data:
            start = (page_no - 1) * PAGE_SIZE
            last = page_no * PAGE_SIZE

            color_data = ColorApi.check_data(color_value=color)
            if color_data:
                post_data = []
                color_filter_data = AttachColorApi.get_image_by_color(color_data.id)
                total = color_filter_data.count()
                if last > total:
                    last = total

                #总页数
                total_page = int(math.ceil(total / PAGE_SIZE))
                total_page = 1 and total_page or 1

                color_data = color_filter_data.order_by('-id')[start: last]
                for c in my_iterator(color_data):
                    cover_data = AttachApi().get_cover_by_share(c.share_post_id)
                    if cover_data:
                        #tk数据
                        img_sale_data = AttachFlagApi.get_goods_by_image(c.post_image_id)
                        if img_sale_data:
                            img_sale_data = img_sale_data[0]
                        else:
                            img_sale_data = None

                        cover_data.update({
                            'cover': c.post_image.path,
                            'cover_id': c.post_image_id,
                            'sale_data': img_sale_data
                        })

                        post_data.append(cover_data)

                color_share_data = {'share': post_data, 'total_page': total_page, 'total': total}

                MtCache('search_color').set(color_share_data, color=color, page=page_no)

        return color_share_data

    #用户订阅的
    @staticmethod
    def get_by_user_subscribe(sub_data, page_no):
        post_data = []
        start = (page_no - 1) * PAGE_SIZE
        last = page_no * PAGE_SIZE
        total = AttachTagApi.get_user_subscribe_count(sub_data)
        if last > total:
            last = total

        tag_data = AttachTagApi.get_user_subscribe(sub_data, start, last)
        for tag in my_iterator(tag_data):
            cover_data = AttachApi().get_cover_by_share(tag[2])

            #tk数据
            img_sale_data = AttachFlagApi.get_goods_by_image(tag[0])
            if img_sale_data:
                img_sale_data = img_sale_data[0]
            else:
                img_sale_data = None

            cover_data.update({
                'cover': tag[1],
                'cover_id': tag[0],
                'sale_data': img_sale_data
            })
            post_data.append(cover_data)

        sub_share_data = {'share': post_data, 'total': total}

        return sub_share_data

    #add
    @staticmethod
    def add(title, content, cate_data, user, is_video=0, video=None, scheduled=False):
        new_post = Post(
            title=title,
            content=content,
            cate=cate_data,
            user=user,
            is_video=is_video,
            video=video,
            scheduled_enbale=scheduled
        )
        new_post.save()

        return new_post

    #商家的帖子
    @staticmethod
    def get_by_business():
        return Post.objects.filter(user__group_id=3).order_by('-id')[0:80]

    #获取来源标记
    @staticmethod
    def get_origin(share_id):
        result = []
        #淘客
        ori_data = PostOrign.objects.filter(share_post_id=share_id)
        for ori in ori_data:
            result.append({'user': ori.orign_user, 'role': ori.user_role.name})

        return result

    #更新来源数据
    @staticmethod
    def add_origin(share_data, orign_user, role_data, user):
        if not orign_user:
            orign_user = user.username

        if share_data and role_data:
            new_sc = PostOrign(share_post=share_data, orign_user=orign_user, user_role=role_data,
                               add_user=user)
            new_sc.save()

            return True
        return False